#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
云顶之弈LangChain Agent启动器
智能、自主、基于Agent架构的AI助手
"""

import os
import sys
import asyncio
import json
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def load_config():
    """加载配置文件"""
    config_file = project_root / "config.json"

    if not config_file.exists():
        # 如果配置文件不存在，从模板复制
        template_file = project_root / "config_template.json"
        if template_file.exists():
            with open(template_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
        else:
            # 创建默认配置
            config = {
                "openai_api_key": "",
                "model": "gpt-3.5-turbo",
                "temperature": 0.1,
                "enable_agent": True,
                "enable_fallback": True
            }
    else:
        with open(config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)

    return config

def check_environment():
    """检查环境配置"""
    print("检查运行环境...")

    # 检查Python版本
    python_version = sys.version_info
    print(f"   Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")

    # 检查依赖
    required_packages = [
        "langchain",
        "langchain-openai",
        "langchain-community",
        "pydantic",
        "aiohttp",
        "requests"
    ]

    missing_packages = []
    for package in required_packages:
        try:
            __import__(package.replace("-", "_"))
        except ImportError:
            missing_packages.append(package)

    if missing_packages:
        print(f"   ⚠️ 缺少依赖包: {', '.join(missing_packages)}")
        print("   💡 运行: pip install langchain langchain-openai langchain-community pydantic aiohttp requests")
        return False

    print("   ✅ 依赖检查通过")
    return True

def setup_api_key():
    """设置API密钥"""
    print("\n🔑 API密钥配置")
    print("-" * 30)

    config = load_config()

    if not config.get("openai_api_key"):
        print("⚠️ 未找到OpenAI API密钥")
        print("\n📝 获取API密钥的方法:")
        print("1. 访问 https://platform.openai.com/api-keys")
        print("2. 登录OpenAI账户")
        print("3. 创建新的API密钥")
        print("4. 复制密钥并粘贴到下面")

        api_key = input("\n请输入你的OpenAI API密钥: ").strip()

        if api_key:
            config["openai_api_key"] = api_key

            # 保存配置
            config_file = project_root / "config.json"
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)

            print("✅ API密钥已保存")
            return True
        else:
            print("❌ 未输入API密钥，将使用模拟模式")
            return False
    else:
        print("✅ 已配置API密钥")
        return True

async def main():
    """主函数"""
    print("云顶之弈LangChain Agent智能助手")
    print("=" * 50)

    # 检查环境
    if not check_environment():
        input("\n依赖检查失败，请安装缺少的包后重试。按回车键退出...")
        return

    # 设置API密钥
    has_api_key = setup_api_key()

    # 导入并启动助手
    try:
        from agent_assistant import AgentTFTAssistant

        print("\n🚀 启动智能助手...")
        assistant = AgentTFTAssistant()
        await assistant.run()

    except KeyboardInterrupt:
        print("\n👋 程序被用户中断")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(main())